//
//  AppDelegate.m
//  project
//
//  Created by 黄建华 on 2017/9/23.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "SNNavigationViewController.h"
#import "CustomTabBar.h"
#import "LoginViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "FileModelEntity.h"
#import <Bugly/Bugly.h>
#import "FileModelEntity.h"
#import "OTAUpdateFirmwareNordicVc.h"
#import "IQKeyboardManager.h"
#import "KeyChainStore.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate, UIAlertViewDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSDictionary* defaults = [NSDictionary dictionaryWithObjects:@[@"2.3", [NSNumber numberWithInt:12], @NO] forKeys:@[@"key_diameter", @"dfu_number_of_packets", @"dfu_force_dfu"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
    
    [NSThread sleepForTimeInterval:0.5];
    // Override point for customization after application launch.
    self.window                 = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [XMProtectorManager openAllCrashProtectorWithBlock:^(NSException *exception, NSString *crashLog, XMCrashProtectorType crashType) {
        NSLog(@"🙂防错🙂CrashLog>>>>>%@",crashLog);
    }];
    
    [Bugly startWithAppId:@"dfd290d4a7"];
    //检查设备模型
    [[ShareData sharedInstance]checkDeviceModel];
    
    [IQKeyboardManager sharedManager].enable = YES;
    [self createVideoFloders];
    //注册通知
    if (IOS10_OR_LATER) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound+UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError *_Nullable error) {
        }];
    } else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    // 状态栏设置为白色文字
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
//    if ([HASLOGIN getBOOLValue]) {
//        [SN_Net getUserInfoWithSuccess:^(id object) {
//            UserInfoModel *model = object;
//            [KK_LastUser setObjectValue:model.user_id];
//        } fail:^(id object) {
//
//        }];
//        [kK_App enterMainVc];
//    } else {
//        [self enterLoginVc];
//    }
    [self localEnterMain];

    [[ThirdLogin sharedInstance] registerActivePlatforms];
    
    [APPFIRST setBOOLValue:YES];
    [self.window makeKeyAndVisible];
    if (@available(iOS 13, *)) {
       [self.window setOverrideUserInterfaceStyle:UIUserInterfaceStyleLight];
    }
    
    [self getFontNames];
//    [self getAppVersion];
    
    return YES;
}

- (void)getAppVersion
{
    NSString *link = @"/user/appversion";
    MKNetworkEngine    *engine = [[MKNetworkEngine alloc] initWithHostName:@"localhost:9090" customHeaderFields:nil];
    MKNetworkOperation *op     = [engine operationWithPath:link params:nil httpMethod:@"GET" ssl:NO];
    
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSString *respon = operation.responseString;
        NSLog(@"🙂>>>>>>%@",respon);
//        NSDictionary *dic = [self dictionaryWithJsonString:respon];
//        if ([dic[@"ret"] integerValue]==401) {
////            SHOWMBProgressHUD(nil, SN_Text(dic[@"message"]), nil, NO, 2.0);
////            [kK_App enterLoginVc];
//            return ;
//        }

    } errorHandler:^(MKNetworkOperation *errorOp, NSError *err) {

        
    }];
    [engine enqueueOperation:op];
}

- (void)getFontNames
{
    NSArray *familyNames = [UIFont familyNames];
    
    for (NSString *familyName in familyNames) {
        printf("🙂🙂🙂familyNames = %s\n",[familyName UTF8String]);
        
        NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
        
        for (NSString *fontName in fontNames) {
            printf("🙂🙂🙂\tfontName = %s\n",[fontName UTF8String]);
        }
    }
}


- (void)localEnterMain
{
//    if ([SN_USER.user_id isEqualToString:@"GetFit3"]) {
//         [self touristLoginClickFirst];
//        [NSThread sleepForTimeInterval:0.5];
//    }

    [self enterMainVc];
}

// 游客登录
- (void)touristLoginClick {
    [SN_Net loginOnWithOpenId:KK_DeviceUUID withOpenType:@"guest" Success:^(id object) {
         [LOGINACCOUNT setObjectValue:@"游客登录"];
         [self loginFinish:object];
     } fail:^(id object) {
        
     }];
}

- (void)touristLoginClickFirst{
    [SN_Net loginOnWithOpenId:KK_DeviceUUID withOpenType:@"guest" Success:^(id object) {
         [LOGINACCOUNT setObjectValue:@"游客登录"];
         [self loginFinish:object];
        [kK_App enterMainVc];
     } fail:^(id object) {
         [kK_App enterMainVc];
     }];
}

- (void)loginFinish:(id)object {
    NSLog(@"登录成功>>>>>");
    UserInfoModel *model    = object;
    NSString      *account  = [LOGINACCOUNT getObjectValue];
    NSString      *passWord = [LOGINPASSWORD getObjectValue];
    [KK_LastUser setObjectValue:model.user_id];
   
    SN_USER.loginAccount  = account;
    SN_USER.loginPassword = passWord;
    SN_USER.portrait      = model.portrait;
    SN_USER.is_first      = model.is_first;
    SN_USER.user_id       = model.user_id;
    SN_USER.access_token  = model.access_token;
    SN_USER.weight        = model.weight;
    SN_USER.height        = model.height;
    SN_USER.gender        = model.gender;
    [SN_USER updateToDB];
     [SN_PublicClass updateUser];

    [SN_Net downImageHeardWith];

//    [SN_Net getUserInfoWithSuccess:^(id object) {
//         [weakSelf getUserInfoFinish:object];
//     } fail:^(id object) {
//     }];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

- (void)enterLoginVc {
    LoginViewController        *loginVc  = [[LoginViewController alloc]init];
    SNNavigationViewController *customVC = [[SNNavigationViewController alloc] initWithRootViewController:loginVc];
    
    self.window.rootViewController = customVC;
}

- (void)enterMainVc {
    if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:HHH_Text(@"请允许s-Band激活推送功能") message:HHH_Text(@"s-Band请求您激活来电、短信、APP推送功能") delegate:self cancelButtonTitle:HHH_Text(@"拒绝") otherButtonTitles:HHH_Text(@"允许"), nil];
        alertView.delegate = self;
        [alertView show];
    }
    [HASLOGIN setBOOLValue:YES];
    CustomTabBar               *guide    = [[CustomTabBar alloc]init];
    SNNavigationViewController *customVC = [[SNNavigationViewController alloc] initWithRootViewController:guide];
    
    [self loadTextFontColor];
    self.window.rootViewController = customVC;
}

- (void)pushUpdateVc {
    if ([HASLOGIN getBOOLValue]) {
        OTAUpdateFirmwareNordicVc           *vc       = [[OTAUpdateFirmwareNordicVc alloc] init];
        if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
        {
            [vc fjwUpdateFirmwareInit];
            KK_BLEConnect.fwxOta = YES;
        }
        if ([KK_BLEModel.chip containsString:@"nrf"]) {
            [vc nrfUpdateFirmwareInit];
        }
        SNNavigationViewController *customVC = [[SNNavigationViewController alloc] initWithRootViewController:vc];
        self.window.rootViewController = customVC;
    }
}

- (void)loadTextFontColor {
    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
    NSString       *str   = [userD objectForKey:@"themeColor"];
    NSInteger      i      = 0;
    
    if (!str) {
        i = 0xbe9f61;
    } else {
        if ([str isEqualToString:@"默认"]) {
            i = 0xbe9f61;
        } else if ([str isEqualToString:@"暗红"]) {
            i = 0xc50b30;
        } else if ([str isEqualToString:@"浅蓝"]) {
            i = 0x84b4e4;
        } else if ([str isEqualToString:@"深蓝"]) {
            i = 0x0195d3;
        } else if ([str isEqualToString:@"蓝黑"]) {
            i = 0xbe9f61;
        } else if ([str isEqualToString:@"鲜黄"]) {
            i = 0xfecf29;
        } else if ([str isEqualToString:@"橙黄"]) {
            i = 0xf66d1f;
        } else if ([str isEqualToString:@"紫色"]) {
            i = 0x3e2581;
        } else if ([str isEqualToString:@"粉红"]) {
            i = 0xff0066;
        } else if ([str isEqualToString:@"蓝色"]) {
            i = 0x0000fe;
        }
    }
    [userD setInteger:i forKey:@"themeHex"];
    [userD synchronize];
}

- (void)createVideoFloders {    // 通知不用上传备份
    [XYSandbox createDirectoryAtPath:[[XYSandbox docPath] stringByAppendingPathComponent:@"/db/"]];
    [XYSandbox createDirectoryAtPath:[[XYSandbox docPath] stringByAppendingPathComponent:@"/dbimg/"]];
    [[[XYSandbox docPath] stringByAppendingPathComponent:@"/db/"] addSkipBackupAttributeToItem];
    [[[XYSandbox docPath] stringByAppendingPathComponent:@"/dbimg/"] addSkipBackupAttributeToItem];
}

//ios10
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    if ([notification.request.identifier isEqualToString:@"findPhone"]) {
        return;
    }
    
    if ([notification.request.identifier isEqualToString:@"latestRealSportData"]) {
        return;
    }
   
//    if ([notification.request.identifier isEqualToString:@"SynchronousBigData"]) {
//        return;
//    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

- (void)latestRealSportDataNotification:(nullable NSString *)notiTitle subtitle:(nullable NSString *)subtitle identifier:(nullable NSString *)identifier {
    if (IOS10_OR_LATER) {
        //ios 10
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:notiTitle arguments:nil];
        content.subtitle = subtitle;
        content.sound = [UNNotificationSound defaultSound];
        //content.badge = [NSNumber numberWithInteger:1];
        UNTimeIntervalNotificationTrigger *trigger    = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
        UNNotificationRequest             *request    = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
        [center addNotificationRequest:request withCompletionHandler:nil];
    } else {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.timeZone       = [NSTimeZone localTimeZone];
        notification.fireDate       = [NSDate dateWithTimeIntervalSinceNow:3];
        notification.repeatCalendar = [NSCalendar currentCalendar];
        notification.alertBody      = SN_Text(@"步数");
        notification.alertAction    = @"打开应用";
        notification.soundName      = UILocalNotificationDefaultSoundName;
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
}

//ios8
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // 2019.05.24 APP 设置设备实时运动数据的上传方式
    dispatch_async(dispatch_get_main_queue(), ^{
        [KK_BLESend sendSetRealSportDataType:YES block:^(id object, KKBLEAcceptType type) {
            
        }];
    });
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 2019.05.24 APP 设置设备实时运动数据的上传方式
    dispatch_async(dispatch_get_main_queue(), ^{
        [KK_BLESend sendSetRealSportDataType:NO block:^(id object, KKBLEAcceptType type) {
            
        }];
    });
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"APP异常退出applicationWillTerminate>>>>>>>");
    BOOL exit = [@"sendControlTakePhotoState" getBOOLValue];
    if (exit) {
        [KK_BLESend sendControlTakePhotoState:NO WithUpdateBlock:^(id object, KKBLEAcceptType type) {
        }];
        [KK_BLEConnect disConnect];
    }
}

@end

